package managers;

import java.sql.SQLException;
import java.util.List;

import stores.OperatorStore;
import stores.OperatorStoreImpl;
import stores.PasswordMangler;
import workspace.Workspace;
import beans.Operator;

public class OperatorManagerImpl implements OperatorManager {

	private OperatorStore operatorStore = new OperatorStoreImpl();

	@Override
	public Operator loginOperator(Workspace workspace, String felhasznaloNev,
			String jelszo) throws SQLException {
		Operator aktualisOperator = operatorStore.loadOperatorByUsername(
				workspace, felhasznaloNev, true);
		if (aktualisOperator == null) {
			return null;
		}
		if (PasswordMangler.isValid(jelszo, aktualisOperator.getJelszoHash())) {
			aktualisOperator.setJelszoHash(null);
			return aktualisOperator;
		} else {
			return null;
		}
	}

	@Override
	public Operator insertOperator(Workspace workspace, Operator newOperator)
			throws SQLException {
		newOperator.setJelszoHash(PasswordMangler.mangle(newOperator
				.getJelszoHash()));
		Operator operator = operatorStore
				.insertOperator(workspace, newOperator);
		return operator;
	}

	@Override
	public Operator updateOperator(Workspace workspace, Operator updatedOperator)
			throws SQLException {
		if (updatedOperator.getJelszoHash() != null) {
			updatedOperator.setJelszoHash(PasswordMangler
					.mangle(updatedOperator.getJelszoHash()));
		}
		Operator operator = operatorStore.updateOperator(workspace,
				updatedOperator);
		return operator;
	}

	@Override
	public boolean deleteOperator(Workspace workspace, long userId)
			throws SQLException {
		return operatorStore.deleteOperator(workspace, userId);
	}

	@Override
	public Operator loadOperatorByUsername(Workspace workspace,
			String felhasznaloNev, boolean isLogin) throws SQLException {
		return operatorStore.loadOperatorByUsername(workspace, felhasznaloNev,
				isLogin);
	}

	@Override
	public List<Operator> loadOperatorLista(Workspace workspace)
			throws SQLException {
		return operatorStore.loadOperatorLista(workspace);
	}

}
